﻿namespace InkType.ViewModel

open InkType.ViewModel.SavedTypefaces
open InkType.ViewModel.Xml
open System
open System.Collections.Generic
open System.Collections.ObjectModel
open System.Windows
open System.Windows.Ink
open System.Windows.Input
open System.Windows.Media


type InkTypeViewModel private (__) =
    inherit DependencyObject ()

    let dc =
        try
            SavedTypefaces.GetDataContext ()
        with
        | ex ->
            let _ = MessageBox.Show (ex.Message, "Error accessing database file", MessageBoxButton.OK, MessageBoxImage.Error)
            raise ex

    let characterBlocks =
        try
            XmlLoad "CharacterBlocks.xml"
            |> CharacterBlock.FromXml
        with
        | _ ->
            Seq.empty

    let typefaceCollection =
        ObservableCollection<TypefaceViewModel> (
            match dc.Typeface |> Array.ofSeq with
            | [| |] ->
                let typeface =
                    TypefaceModel (
                        Name = "NewTypeface",
                        TypefaceID = Guid.NewGuid ())
                dc.Typeface.InsertOnSubmit typeface
                dc.DataContext.SubmitChanges ()
                [| typeface |]
            | typefaces -> typefaces
            |> Seq.map (fun typeface -> TypefaceViewModel (typeface, dc, characterBlocks))
            |> Seq.sortBy (fun typefacevm -> -typefacevm.Timestamp))

    static member val SelectedTypefaceProperty =
        Dp.reg<TypefaceViewModel, InkTypeViewModel> "SelectedTypeface"
            (Dp.Meta (
                null,
                fun (x : InkTypeViewModel) (oldv : TypefaceViewModel, newv) ->
                    if oldv <> null then oldv.OnExit ()
                    newv.UpdateTimestamp ()))

    new () as x =
        InkTypeViewModel (())
        then
            x.SelectedTypeface <- (x.Typefaces :> IList<_>).[0]

    member internal x.DataContext = dc

    member x.SelectedTypeface
        with get () = x.GetValue InkTypeViewModel.SelectedTypefaceProperty :?> TypefaceViewModel
        and set (v : TypefaceViewModel) = x.SetValue (InkTypeViewModel.SelectedTypefaceProperty, box v)

    member val AddNewTypefaceCommand =
        fun () ->
            let typefaceModel =
                TypefaceModel (
                    Name = "NewTypeface",
                    TypefaceID = Guid.NewGuid ())
            dc.Typeface.InsertOnSubmit typefaceModel
            dc.DataContext.SubmitChanges ()

            let typefaceVM = TypefaceViewModel (typefaceModel, dc, characterBlocks)
            typefaceCollection.Add typefaceVM

        |> Command.Relay

    member x.OnExit () =
        typefaceCollection
        |> Seq.iter (fun typeface ->
            typeface.OnExit ())

    member x.Typefaces = typefaceCollection

